package fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigchun.seeland.AboutUsActivity;
import com.bigchun.seeland.BrandActivity;
import com.bigchun.seeland.EditInfoActivity;
import com.bigchun.seeland.GongShiActivity;
import com.bigchun.seeland.LoginActivity;
import com.bigchun.seeland.MessageListActivity;
import com.bigchun.seeland.MyCollectActivity;
import com.bigchun.seeland.R;
import com.bigchun.seeland.SelectLanguageActivity;
import com.facebook.login.LoginManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import bean.ContentDataBean;
import myapp.MyApp;
import util.GlideUtils;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;
import util.SystemStatusManager;
import util.saveImagUtil;

public class MyFragment extends Fragment {

    private View view;
    private Context mcontext;
    private LinearLayout ll_message;
    private LinearLayout ll_showprice;
    private View line_price;
    private View line_pinpai;
    private ImageView img_userlogo;
    private LinearLayout ll_select_language;
    private LinearLayout ll_select_brand;
    private LinearLayout ll_collect;
    private LinearLayout ll_edit_info;
    private LinearLayout ll_about;
    private LinearLayout ll_gongshi;
    Intent intent = null;
    private Switch switch_button;
    private SharedPreferences sharedPreferences;
    private MyApp myapp;
    private String token;
    private String level = "0";
    private String nickname;
    private String mobile;
    private TextView tv_phone;
    private TextView tv_name;
    private TextView tv_logout;
    private String status;
    private String msgstr;
    private String avatar;
    private String email = "";
    private String apptype = "";
    private String textData;
    private String change_app;
    private String is_show_money;
    private String is_show_formula = "";
    private View line_gongshi;
    private String gongshiUrl = "";
    private String please_retry = "";
    private Bitmap thumb;
    private ContentDataBean.DataBean textContent;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_my, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        setTranslucentStatus();
        //步骤1：创建一个SharedPreferences对象
        sharedPreferences = mcontext.getSharedPreferences("userInfo",Context.MODE_PRIVATE);
        textData = sharedPreferences.getString("textData", "");
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        level = sharedPreferences.getString("level", "");
        initView();
        initLin();
        getData();
        getgongshiData();
        return view;

    }



    private void initView() {
        img_userlogo = view.findViewById(R.id.img_userlogo);
        ll_message = view.findViewById(R.id.ll_message);
        ll_showprice = view.findViewById(R.id.ll_showprice);
        line_price = view.findViewById(R.id.line_price);
        ll_select_language = view.findViewById(R.id.ll_select_language);
        ll_select_brand = view.findViewById(R.id.ll_select_brand);
        line_pinpai = view.findViewById(R.id.line_pinpai);
        ll_collect = view.findViewById(R.id.ll_collect);
        ll_edit_info = view.findViewById(R.id.ll_edit_info);
        ll_about = view.findViewById(R.id.ll_about);
        ll_gongshi = view.findViewById(R.id.ll_gongshi);
        line_gongshi = view.findViewById(R.id.line_gongshi);
        switch_button = view.findViewById(R.id.switch_button);
        boolean isshowprice = sharedPreferences.getBoolean("isshowprice", false);
        //显示上次保存的是否显示价格的状态
        switch_button.setChecked(isshowprice);

        tv_phone = view.findViewById(R.id.tv_phone);
        tv_name = view.findViewById(R.id.tv_name);
        tv_logout = view.findViewById(R.id.tv_logout);
        if ("1".equals(level)){
            ll_showprice.setVisibility(View.VISIBLE);
            line_price.setVisibility(View.VISIBLE);
        }else if ("0".equals(level)){
            ll_showprice.setVisibility(View.GONE);
            line_price.setVisibility(View.GONE);
        }
        TextView tv_center_person = view.findViewById(R.id.tv_center_person);
        TextView tv_showprice = view.findViewById(R.id.tv_showprice);
        TextView tv_messagelist = view.findViewById(R.id.tv_messagelist);
        TextView tv_collect = view.findViewById(R.id.tv_collect);
        TextView tv_change_lan = view.findViewById(R.id.tv_change_lan);
        TextView tv_change_pinpai = view.findViewById(R.id.tv_change_pinpai);
        TextView tv_gongshi = view.findViewById(R.id.tv_gongshi);
        TextView tv_about = view.findViewById(R.id.tv_about);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        please_retry = textContent.getPlease_retry();
        if (textContent != null){
            tv_center_person.setText(textContent.getPersonal());
            tv_showprice.setText(textContent.getShow_price());
            tv_messagelist.setText(textContent.getMessage_list());
            tv_collect.setText(textContent.getGoods_collect());
            tv_change_lan.setText(textContent.getLanguage_change());
            tv_change_pinpai.setText(textContent.getBrand_change());
            tv_gongshi.setText(textContent.getGongshibaojia());
            tv_about.setText(textContent.getAbout_us());
            tv_logout.setText(textContent.getLogout());
        }


        //TODO    判断品牌切换显示还是隐藏
    }
    private void initLin() {
        switch_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                boolean isshowprice = sharedPreferences.getBoolean("isshowprice", false);
                if (isshowprice){
                    showprice("0");
                }else{
                    showprice("1");
                }
            }
        });

        img_userlogo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                saveImagUtil.showDiaLog(mcontext,avatar,textContent);
                return true;
            }
        });

        ll_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mcontext, MessageListActivity.class);
                startActivity(intent);
            }
        });
        ll_select_language.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mcontext, SelectLanguageActivity.class);
                startActivity(intent);
            }
        });
        ll_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mcontext, MyCollectActivity.class);
                startActivity(intent);
            }
        });
        ll_edit_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mcontext, EditInfoActivity.class);
                intent.putExtra("imgurl",avatar);
                startActivity(intent);
            }
        });
        ll_select_brand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mcontext, BrandActivity.class);
                startActivity(intent);
            }
        });
        ll_about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(mcontext, AboutUsActivity.class);
                startActivity(intent);
            }
        });
        ll_gongshi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO   公式
                if (!"".equals(gongshiUrl)){
                    intent = new Intent(mcontext, GongShiActivity.class);
                    intent.putExtra("url",gongshiUrl);
                    startActivity(intent);
                }else{
                    Toast.makeText(mcontext,please_retry,Toast.LENGTH_LONG).show();
                }

            }
        });
        tv_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String mobile = sharedPreferences.getString("mobile", "");
                logout(mobile);
            }
        });
    }
    private void getData() {
        String url = myapp.getWebConfig() + "/api/user/my_info";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    nickname = data.getString("nickname");
                    mobile = data.getString("mobile");
                    avatar = data.getString("avatar");
                    email = data.getString("email");
                    is_show_formula = data.getString("is_show_formula");
                    is_show_money = data.getString("is_show_money");

                    change_app = data.getString("change_app");
                    sharedPreferences.edit().putString("email",email).commit();


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void getgongshiData() {
        String url = myapp.getWebConfig() + "/api/index/formula";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
//                        handler.sendMessage(msg);
                        return;
                    }
                    gongshiUrl = jsonObject.getString("data");



                    msg.arg1 = 6;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
//                    msg.arg1 = 1;
//                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void logout(String phone) {
        String url = myapp.getWebConfig() + "/api/user/logout";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("mobile", phone);
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }

                    String str = jsonObject.getString("msg");
                    msg.obj = str;
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void showprice(String type) {
        String url = myapp.getWebConfig() + "/api/user/is_show_money";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type", type);
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 5;
                        handler.sendMessage(msg);
                        return;
                    }

                    msgstr = jsonObject.getString("msg");
                    JSONObject data = jsonObject.getJSONObject("data");
                    status = data.getString("status");
                    is_show_money = data.getString("is_show_money");
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(mcontext,str,Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(mcontext,textContent.getNet_error(),Toast.LENGTH_LONG).show();
                    break;
                case 2:

                    tv_name.setText(nickname);
                    tv_phone.setText(mobile);
                    //显示价格一栏目=1显示   不为1不显示
                    GlideUtils.loadCircleImage(mcontext,avatar,img_userlogo);
                    // change_app 0当前用户为单平台用户 1当前用户可以切换平台
                    if ("0".equals(change_app)){
                        ll_select_brand.setVisibility(View.GONE);
                        line_pinpai.setVisibility(View.GONE);
                    }else if ("1".equals(change_app)){
                        ll_select_brand.setVisibility(View.VISIBLE);
                        line_pinpai.setVisibility(View.VISIBLE);
                    }
                    if ("0".equals(is_show_formula)){
                        ll_gongshi.setVisibility(View.GONE);
                        line_gongshi.setVisibility(View.GONE);
                    }else if ("1".equals(is_show_formula)){
                        ll_gongshi.setVisibility(View.VISIBLE);
                        line_gongshi.setVisibility(View.VISIBLE);
                    }
                    SharedPreferences.Editor editor2 = sharedPreferences.edit();
                    if ("0".equals(is_show_money)){
                        //关
                        switch_button.setChecked(false);
                        editor2.putBoolean("isshowprice", false).commit();
                    }else if ("1".equals(is_show_money)){
                        //开
                        switch_button.setChecked(true);
                        editor2.putBoolean("isshowprice", true).commit();
                    }


                    break;
                case 3:

                    sharedPreferences.edit().putString("username", "").commit();
                    sharedPreferences.edit().putString("nickname", "").commit();
                    sharedPreferences.edit().putString("mobile", "").commit();
                    sharedPreferences.edit().putString("score", "").commit();
                    sharedPreferences.edit().putString("token", "").commit();
                    sharedPreferences.edit().putString("user_id", "").commit();
                    sharedPreferences.edit().putString("level", "").commit();

                    LoginManager.getInstance().logOut();

//                    sharedPreferences.edit().putString("language","").commit();
                    String strcontent = (String) msg.obj;
                    Toast.makeText(mcontext,strcontent,Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(mcontext, LoginActivity.class);
                    mcontext.startActivity(intent);
                    myapp.destoryActivity("主页面");
                    break;
                case 4:
                    Toast.makeText(mcontext, msgstr, Toast.LENGTH_LONG).show();
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                        //步骤3：将获取过来的值放入文件    false是关闭   true是开启
                    boolean isshowprice = sharedPreferences.getBoolean("isshowprice", false);
                    boolean flaga = !isshowprice;
                        editor.putBoolean("isshowprice", flaga).commit();
                        switch_button.setChecked(flaga);
                    EventBus.getDefault().post(new OrderEventMessage("刷新数据"));

                    break;
                case 5:
                    SharedPreferences.Editor editor1 = sharedPreferences.edit();
                    //步骤3：将获取过来的值放入文件    false是关闭   true是开启
                    editor1.putBoolean("isshowprice", false).commit();
                    boolean isshowprice1 = sharedPreferences.getBoolean("isshowprice", false);
                    switch_button.setChecked(isshowprice1);

                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intentl = new Intent(mcontext, LoginActivity.class);
                        mcontext.startActivity(intentl);
                        myapp.destoryActivity("主页面");
                    }
                    break;

            }
        }
    };
private boolean islogin = false;





    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getActivity().getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(getActivity());
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    @Override
    public void onResume() {
        super.onResume();
        MyLog.e("我的","onResume");
        getData();
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("我的","onHiddenChanged     "+hidden);
        if (!hidden){
            getData();
        }
    }


}
